package com.blog.controller;

import com.blog.common.result.R;
import com.blog.common.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class CommonConfig {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")

    // 返回图片的url
    public R upload(MultipartFile file) {
        log.info("开始上传文件");
        String name = file.getOriginalFilename();
        assert name != null;
        String[] split = name.split("\\.");
        // uuid + 文件的后缀名来保证文件不会重复
        String objectName = UUID.randomUUID() + "." + split[split.length - 1];
        try {
            String url = aliOssUtil.upload(file.getBytes(), objectName);
            return R.success(url);
        } catch (IOException e) {
            log.error("上传失败", e);
        }
        return R.error("文件上传失败");
    }
}
